package com.auditlog.format.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.auditlog.datasource.db.SqlType;
import com.auditlog.datasource.struct.FieldChangeLog;
import com.auditlog.datasource.struct.RecordImage;
import com.auditlog.datasource.struct.RowChangeLog;
import com.auditlog.datasource.struct.TableRecord;
import com.auditlog.format.AbstractRecordImageFormat;
import org.checkerframework.checker.units.qual.K;

import java.util.*;

public class DeleteRecordImageFormat extends AbstractRecordImageFormat {

    @Override
    public void doFormat(RecordImage recordImage) {
        TableRecord beforeRecord = recordImage.getBeforeRecord();
        TableRecord afterRecord = recordImage.getAfterRecord();
        Map<String, List<Object>> before = beforeRecord.getRows();
        Map<String, List<Object>> after = afterRecord.getRows();
        String delimiter = beforeRecord.getDelimiter();
        Set<String> removeKey = new HashSet<>();
        if (CollectionUtil.isNotEmpty(after)) {
            after.forEach((k, v) -> {
                if (before.containsKey(k)) {
                    removeKey.add(k);
                }
            });
        }
        List<List<Object>> possibleUpdateOrDeletePks = recordImage.getPossibleUpdateOrDeletePks();
        this.removeKey(possibleUpdateOrDeletePks, removeKey, recordImage.getPkColumnsName(), delimiter);
    }

    @Override
    public Map<SqlType, List<RowChangeLog>> changeLog(RecordImage recordImage) throws Exception {
        return this.buildDeleteChangeLog(recordImage);
    }

    @Override
    public SqlType getType() {
        return SqlType.DELETE;
    }
}
